#include <bits/stdc++.h>
using namespace std;
using ll = long long;
using pii = pair<int, int>;
#define rep(i, a, b) for (int i = (a); i <= (b); i++)
#define per(i, a, b) for (int i = (a); i >= (b); i--)
#define endl '\n'
const int N = 2e5 + 5;

int n, m;
int a[N], b[N];
int fastpow(int b, int p, int mod) {
  int res = 1 % mod;
  while (p) {
    if (p & 1) res = res * b % mod;
    b = b * b % mod;
    p >>= 1;
  }
  return res;
}
int main() {
  ios::sync_with_stdio(0), cin.tie(0), cout.tie(0);
  int t;
  cin >> t;
  while (t--) {
    cin >> m >> n;
    rep(i, 1, n) cin >> a[i] >> b[i];
    int res = 0;
    rep(i, 1, n) res = (res + fastpow(a[i] % m, b[i], m)) % m;
    cout << res << endl;
  }
  return 0;
}